import os
import sys
import subprocess

OSS_CONFIG = 'oss_config'

def printHelp(command):
    if command == '-t':
        print("-t: 上传文件到OSS：oss_file_path, source_dir, oss_path, file_type")
        print( "UploadFileToOss.py -t '{oss_file_path}' '{source_dir}' '{oss_path}' '{file_type}' ")
        exit(0)
    elif command == '-n':
        print("-n: 上传文件到OSS：oss_file_path, source_dir, oss_path, file_name_type")
        print( "UploadFileToOss.py -n '{oss_file_path}' '{source_dir}' '{oss_path}' '{file_name_type}' ")
        exit(0)
    elif command == '-u':
        print("-u: 上传文件到OSS：oss_file_path, file_path, oss_path, oss_command")
        print("UploadFileToOss.py -u '{oss_file_path}' '{file_path}' '{oss_path}' '{oss_command}' ")
        exit(0)
    elif command == '-c':
        print("-c: OSS文件拷贝：oss_file_path, oss_path, oss_target_path, oss_command")
        print("UploadFileToOss.py -c '{oss_file_path}' '{oss_path}' '{oss_target_path}' '{oss_command}' ")
        exit(0)
    else:
        print("Use: UploadFileToOss.py -[t|n|u|c]")
        print("-t: 上传文件到OSS：oss_file_path, source_dir, oss_path, file_type")
        print("UploadFileToOss.py -t '{oss_file_path}' '{source_dir}' '{oss_path}' '{file_type}' ")

        print("-n: 上传文件到OSS：oss_file_path, source_dir, oss_path, file_name_type")
        print( "UploadFileToOss.py -n '{oss_file_path}' '{source_dir}' '{oss_path}' '{file_name_type}' ")

        print("-u: 上传文件到OSS：oss_file_path, file_path, oss_path, oss_command")
        print("UploadFileToOss.py -u '{oss_file_path}' '{file_path}' '{oss_path}' '{oss_command}' ")

        print("-c: OSS文件拷贝：oss_file_path, oss_source_path, oss_target_path, oss_command")
        print("UploadFileToOss.py -c '{oss_file_path}' '{oss_source_path}' '{oss_target_path}' '{oss_command}' ")
        exit(0)

# matching
def findFileType(oss_file_path,source_dir, oss_path,file_type):
    uploadFileToOss(oss_file_path,source_dir, oss_path,f'*{file_type}')

def findFileNameType(oss_file_path,source_dir, oss_path,file_type_name):
    uploadFileToOss(oss_file_path,source_dir, oss_path,file_type_name)

def uploadFileToOss(oss_file_path,source_dir, oss_path,matching):
    tmp_source_dir_list = source_dir.split(os.path.sep)
    source_dir_list = []
    for item in tmp_source_dir_list:
        if (item.find("*") < 0):
            source_dir_list.append(item)

    source = os.path.sep.join(source_dir_list)
    print(f"DEBUG: matching: {matching}")
    shell = os.popen(f"find %s -name {matching} -type f" % source)
    ret = shell.read().strip()
    if len(ret) == 0:
        print("no file find in path %s")
        return

    file_name = ret.split("\n")[0]
    print(f"filename: {file_name}")
    print(f"oss_path: {oss_path}")
    setOssConfig(oss_file_path)
    try:
        print( f"oss_util_mac_64 上传指令：'{oss_file_path}/{getCpuInfo()}_oss_util_mac_64' -c '{oss_file_path}/{OSS_CONFIG}' cp -rf {file_name} {oss_path} --acl private")
        ret_os_system = os.system( f"'{oss_file_path}/{getCpuInfo()}_oss_util_mac_64' -c '{oss_file_path}/{OSS_CONFIG}' cp -rf {file_name} {oss_path} --acl private")
        print(f"ret_os_system:{ret_os_system}")
        if ret_os_system == 0:
            print(f"upload success:{file_name}")
        else:
            print(f"upload fail:{file_name}" )
            exit(0)
    except Exception as e:
        print(f"oss_util_mac_64 上传失败：{e}")
        exit(0)

def uploadCopyFileToOss(oss_file_path, oss_source_path, oss_target_path, oss_command):
    try:
        print( f"oss_util_mac_64 上传指令：'{oss_file_path}/{getCpuInfo()}_oss_util_mac_64' -c '{oss_file_path}/{OSS_CONFIG}' cp -rf {oss_source_path} {oss_target_path} {oss_command}")
        ret_os_system = os.system( f"'{oss_file_path}/{getCpuInfo()}_oss_util_mac_64' -c '{oss_file_path}/{OSS_CONFIG}' cp -rf {oss_source_path} {oss_target_path} {oss_command}")
        print(f"ret_os_system:{ret_os_system}")
        if ret_os_system == 0:
            print(f"upload success:{oss_source_path} {oss_target_path}")
        else:
            print(f"upload fail:{oss_source_path} {oss_target_path}" )
            exit(0)
    except Exception as e:
        print(f"oss_util_mac_64 上传失败：{e}")
        exit(0)

def setOssConfig(oss_file_path):
    file_path = f"/Users/{getUserInfo()}/ossOutputDir"
    print(f"ossOutputDir： {file_path}")
    if not os.path.exists(file_path):
        os.makedirs(file_path)
        print(f"ossOutputDir: {file_path} 已创建")
    else:
        print(f"ossOutputDir: {file_path} 已存在")

    print(f"oss_file_path： {oss_file_path}/{OSS_CONFIG}")

    # 修改配置文件
    with open(f'{oss_file_path}/{OSS_CONFIG}', 'a', encoding='utf-8') as f:
        f.write("\n")
        f.write(f"outputDir={file_path}")

    try:
        with open(f'{oss_file_path}/{OSS_CONFIG}', 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"oss_config:{content}")
    except Exception as e:
        print(f"读取oss_config失败：{e}")
        exit(0)



def getCpuInfo():
    data = subprocess.run(['sysctl', '-n','machdep.cpu.brand_string'], capture_output=True, text=True)
    result =  data.stdout
    print("获取cup信息:", result)
    if 'Apple' in result  :
        return 'm'
    else:
        return 'intel'

def getUserInfo():
    result = subprocess.run(['whoami'], capture_output=True, text=True)
    print("获取用户信息:", result.stdout)
    return result.stdout.replace('\n','').replace('\t','')

# def test():
    #findFileType('/Users/gymd/DevEcoStudioProjects/hm-demo','/Users/gymd/Desktop/维护/cgmartsapp/android/app/build/outputs/apk','oss://geely-admp-test-oss/agp-dev/package/hongmeng/harmony/1.0.2/10002003/','app-release.apk')
    #findFileNameType('/Users/gymd/DevEcoStudioProjects/hm-demo','/Users/gymd/Desktop/维护/cgmartsapp/android/app/build/outputs/apk','','app-release.apk')
    # uploadCopyFileToOss('/Users/gymd/DevEcoStudioProjects/hm-demo','/Users/gymd/Desktop/维护/cgmartsapp/android/app/build/outputs/', 'oss://geely-admp-test-oss/agp-dev/package/hongmeng/harmony/1.0.2/10002003/', '--acl public')

if __name__ == "__main__":
    # test()
    if len(sys.argv) < 2:
        printHelp('error')
    command = sys.argv[1]
    print(f"参数长度：{len(sys.argv)}{sys.argv[0]}{sys.argv}")
    if command == "-t":
        if len(sys.argv) < 6:
            printHelp(command)
        findFileType( sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    elif command == "-n":
        if len(sys.argv) < 6:
            printHelp(command)
        findFileNameType(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    elif command == "-u":
        if len(sys.argv) < 6:
            printHelp(command)
        uploadCopyFileToOss(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    elif command == "-c":
        if len(sys.argv) < 6:
            printHelp(command)
        uploadCopyFileToOss(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
    else:
        printHelp('error')



